package cn.z2huo.leetcode.problem.NO_0004;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.ResourceUtils;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * <p>
 *
 * @author z2huo
 */
class CsvTestDataInit {

    private static final String TEST_DATA_CLASS_PATH =
            ResourceUtils.CLASSPATH_URL_PREFIX + "csv/problem/NO_0004/";

    public List<InputOutput> getTestData() {
        return this.getTestData(1000);
    }

    public List<InputOutput> getTestData(int dataSize) {

        CsvReadConfig csvReadConfig = CsvReadConfig.defaultConfig();
        csvReadConfig.setBeginLineNo(0);

        String filePath = TEST_DATA_CLASS_PATH + "test_data_" + dataSize + ".csv";
        try (InputStreamReader fileReader = new FileReader(ResourceUtils.getFile(filePath));
             CsvReader reader = CsvUtil.getReader(fileReader, csvReadConfig);) {

            CsvData csvData = reader.read();

            List<InputOutput> queryInputOutputList = csvData.getRows().parallelStream()
                    .map(row -> new InputOutput(StrUtil.splitToInt(row.getFirst(), ';'),
                            StrUtil.splitToInt(row.get(1), ';'),
                            Double.parseDouble(row.get(2)))
                    )
                    .toList();

            boolean sortedFlag = queryInputOutputList.stream().allMatch(sortInputOutput ->
                    ArrayUtils.isSorted(sortInputOutput.getArray()) && ArrayUtils.isSorted(sortInputOutput.getArray2())
            );
            if (!sortedFlag) {
                throw new RuntimeException("csv data result array is not sorted");
            }
            return queryInputOutputList;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
